import datetime
import json

from django.conf import settings
from django.http import QueryDict, JsonResponse

from django.views import View

from aijia_rental.utils.views import LoginRequiredJSONMixin
from lina.models import House
from lvhanxun.models import Order


# add_order  and  get order_list
class OrderView(LoginRequiredJSONMixin, View):

    def get(self, request):
        user = request.user
        role = request.GET.get("role")

        if not role:
            return JsonResponse({"errmsg": "无数据",
                                 "errno": "4002"})
        if role not in ["custom", "landlord"]:
            return JsonResponse({"errmsg": "参数错误",
                                 "errno": "4103"})

        try:
            if role == "custom":
                orders = Order.objects.filter(user=user).order_by("-create_time")
            elif role == "landlord":
                houses = House.objects.filter(user=user)
                houses_ids = [house.id for house in houses]
                orders = Order.objects.filter(houses_id__in=houses_ids).order_by("-create_time")
        except Exception:
            return JsonResponse({"errmsg": "数据库查询错误",
                                 "errno": "4001", })
        # print(order.)
        data = []
        for order in orders:
            if order.status == Order.ORDER_STATUS["WAIT_COMMENT"]:
                if role == 'landlord':
                    status = 'ACCEPT'
                else:
                    status = Order.ORDER_STATUS_ENUM[order.status]
            else:
                status = Order.ORDER_STATUS_ENUM[order.status]

            data.append({
                "amount": order.amount,
                "comment": order.comment,
                "ctime": order.create_time,
                "days": order.days,
                "end_date": order.end_date,
                "img_url": settings.QNY_URL + order.house.index_image_url,
                "order_id": order.id,
                "start_date": order.begin_date,
                "status": status,
                "title": order.house.title})

        return JsonResponse({"errmsg": "OK",
                             "errno": "0",
                             "data":{"orders": data} })

    def post(self, request):
        """"add_order"""

        # pull value
        user = request.user
        josn_dict = json.loads(request.body.decode())
        house_id = josn_dict.get("house_id")
        start_date = josn_dict.get("start_date")
        end_date = josn_dict.get("end_date")

        if not all([house_id, start_date, end_date]):
            return JsonResponse({"errno": "4002",
                                 "errmsg": "缺少参数"})

        try:
            start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
            end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")

            # 计算出入住天数
            days = (end_date - start_date).days
        except Exception:
            return JsonResponse({"errno": "4002",
                                 "errmsg": "参数"})

        try:
            house = House.objects.get(id=house_id)
        except Exception:
            return JsonResponse({'errno': "401",
                                 'errmsg': 'house_id查询错误'})

        if user == house.user:
            return JsonResponse({'errno': "4105",
                                 'errmsg': "用户身份错误"})
        try:
            count = Order.objects.filter(begin_date__lt=end_date, end_date__gt=start_date, house=house).count()
        except Exception:
            return JsonResponse({'errno': "401",
                                 'errmsg': '数据库查询错误'})

        if count > 0:
            return JsonResponse({'errno': '4003',
                                 'errmsg': '暂无房间可使用'})

        amount = days * house.price

        try:
            order = Order.objects.create(
                user=user,
                house=house,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house.price,
                amount=amount
            )

            house.order_count += 1
            house.save()
        except Exception:
            return JsonResponse({'errno': "401",
                                 'errmsg': '数据库存储错误'})

        return JsonResponse({'errno': "0",
                             "errmsg": "",
                             "data": order.id})


# 接单和拒单
class IfOrderStatusView(LoginRequiredJSONMixin, View):
    """接单和拒单"""

    def put(self, request, order_id):
        # 接受参数
        user = request.user
        put = QueryDict(request.body)
        action = put.get("action")
        reason = put.get("reason")

        # 验证参数
        if not all([action, order_id]):
            return JsonResponse({"errno": "4002",
                                 "errmsg": "缺少参数"})

        if action not in ["accept", "reject"]:
            return JsonResponse({"errno": "4004",
                                 "errmsg": "数据错误"})

        try:
            orders = Order.objects.filtet(id=order_id,
                                          status=Order.ORDER_STATUS["WAIT_ACCEPT"])

        except Exception:
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})

        for order in orders:
            house = order.house
            if not user != house.user:
                return JsonResponse({"errno": "4103",
                                     "errmsg": "参数错误"})

            # 判断action 是接单还是订单
            if action == 'accept':
                order.status = Order.ORDER_STATUS["WAIT_COMMENT"]
            elif action == 'reject':
                if not reason:
                    return JsonResponse({"errno": "4002",
                                         "errmsg": "无数据"})
                try:
                    order.status = Order.ORDER_STATUS["REJECTED"]
                    order.comment = reason
                except Exception:
                    return JsonResponse({"errno": "4004",
                                         "errmsg": "数据错误"})
            try:
                house.order_count -= 1
                house.save()
            except Exception as e:
                return JsonResponse({'errno': 400,
                                     'errmsg': '增加房屋订单数量失败'})
        return JsonResponse({
            "errno": "0",
            "errmsg": "ok"
        })


# 订单评论
class OrdersCommentView(LoginRequiredJSONMixin, View):
    """订单评论"""

    def put(self, request, order_id):
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get("comment")

        if not comment:
            return JsonResponse({"errno": "4002",
                                 "errmsg": "缺少参数"})

        try:
            order = Order.objects.get(id=order_id,
                                      status=Order.ORDER_STATUS["WAIT_COMMENT"])
        except Exception:
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})

        try:
            house = order.house
            house.order_count += 1
            order.status = Order.ORDER_STATUS["COMPLETE"]
            order.comment = comment
        except Exception:
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})

        return JsonResponse({"errno": "0",
                             "errmsg": "评论成功"})
